package com.time.timespace.filter;

import com.alibaba.fastjson.JSON;
import com.time.timespace.commons.dto.ResponseEntity;
import com.time.timespace.commons.utils.WebUtils;
import com.time.timespace.domain.dto.TokenDTO;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import com.time.timespace.commons.utils.RedisCacheDTO;
import com.time.timespace.domain.dto.UserDetailsDTO;

import java.io.IOException;
import java.util.Objects;

/**
 * @author mjw
 * @date 2024/06/27
 */
@Configuration
public class AuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCacheDTO redisCache;

    public static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationTokenFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //1.获取token header中的token
        String token = TokenDTO.getToken(request);
        if (StringUtils.isBlank(token)) {
            // 放行 让后面的过滤器执行
            filterChain.doFilter(request, response);
            return;
        }

        //3获取userId, redis获取用户信息
        UserDetailsDTO userDetailsDTO = redisCache.getCacheObject(token);
        if (Objects.isNull(userDetailsDTO)) {
            //返回给前端的json
            ResponseEntity<Object> responseResult = ResponseEntity.builder()
                    .timestamp(System.currentTimeMillis())
                    .status(String.valueOf(HttpStatus.UNAUTHORIZED.value()))
                    .message("当前用户未登录！")
                    .data(null).build();
            String json = JSON.toJSONString(responseResult);
            WebUtils.renderString(response, json);
            return;
        }

        //4封装Authentication
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(userDetailsDTO, null, userDetailsDTO.getAuthorities());

        //5存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行，让后面的过滤器执行
        filterChain.doFilter(request, response);
    }

    public RedisCacheDTO getRedisCache() {
        return redisCache;
    }

    public void setRedisCache(RedisCacheDTO redisCache) {
        this.redisCache = redisCache;
    }
}
